package com.imessage.action;

import com.bean.BaseConfig;
import com.bean.ManageUser;
import com.imessage.comm.AdminSession;
import com.imessage.comm.Constants;
import com.imessage.service.BaseService;
import com.imessage.service.RoleMenuService;
import com.imessage.service.TaskService;
import com.imessage.service.WumaService;
import com.imessage.type.BaseConfigCode;
import com.imessage.utils.DateUtil;
import com.imessage.utils.StrUtil;
import com.imessage.web.HttpJson;
import com.imessage.web.Page;
import io.ebean.Expr;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.*;

@Slf4j
public class BaseAction {
    @Autowired
    protected HttpServletRequest request;
    @Autowired
    protected Environment environment;
    @Autowired
    protected BaseService baseService;
    @Autowired
    protected RoleMenuService roleMenuService;
    @Autowired
    protected TaskService taskService;
    @Autowired
    protected WumaService wumaService;

    protected AdminSession getAdminSession(boolean isDebug) {
        if (isDebug) {
            ManageUser manageUser = baseService.findObject(ManageUser.class,
                    Expr.eq("name", "admin"));
            if (manageUser == null) {
                return null;
            }
            AdminSession adminSession = new AdminSession();
            adminSession.setManageUser(manageUser);
            return adminSession;
        }
        HttpSession session = request.getSession();
        Object object = session.getAttribute(Constants.SESSION_ADMIN_CODE);
        return (AdminSession) object;
    }


    protected String getRemortIP() {
        if (request.getHeader("x-forwarded-for") == null) {
            return request.getRemoteAddr().replaceAll(" ", "");
        }
        return request.getHeader("x-forwarded-for").replaceAll(" ", "");
    }

    protected String getBody() {
        try {
            BufferedReader in =
                    new BufferedReader(
                            new InputStreamReader(request.getInputStream(), "UTF-8"));
            CharArrayWriter data = new CharArrayWriter();
            char[] buf = new char[8192];
            int ret;
            while ((ret = in.read(buf, 0, 8192)) != -1) {
                data.write(buf, 0, ret);
            }
            return data.toString();
        } catch (Exception e) {
            System.err.println("接收BODY内容失败：" + e);
        }
        return null;
    }

    protected void copyProperties(Object source, Object target) {
        org.springframework.beans.BeanUtils.copyProperties(source, target, StrUtil.getNullPropertyNames(source));
    }

    protected String getOrder(String orders) {
        StringBuffer ordersb = new StringBuffer();
        if (StringUtils.isBlank(orders)) {
            ordersb.append("updated_time desc");
        } else {
            ordersb.append(orders);
        }
        return ordersb.toString();
    }

    protected HttpJson getJsonForSucc(String msg, String datagrid) {
        return new HttpJson(HttpJson.STATE_SUCCESS, msg, true, datagrid);
    }

    protected HttpJson getJsonForErr(String msg, String datagrid) {
        return new HttpJson(HttpJson.STATE_FAIL, StringUtils.isNotBlank(msg) ? msg : "系统异常", false, datagrid);
    }


    protected String getOrders(String orders, String regex, String replace) {
        if (StringUtils.isBlank(orders)) {
            return "id desc";
        }
        return orders.replaceAll(regex, replace);
    }

    protected String fileUpload(MultipartFile multipartFile){
        if(multipartFile==null){
            return "";
        }
        String fileName = multipartFile.getOriginalFilename();
        if (!fileName.matches("^.+\\.(?i)(xls)$")
                && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
            return "";
        }
        String uploadFile= StrUtil.getOsResourceLoc(environment)+ File.separator+"upload";
        File fileDir = new File(uploadFile);
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
        uploadFile= uploadFile+File.separator+DateUtil.getDateTime(new Date(),"yyyyMMdd");
        fileDir = new File(uploadFile);
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
        String name=UUID.randomUUID().toString().replaceAll("-", "");
        return fileUpload(multipartFile,uploadFile,name,true);
    }


    /***
     *
     * @param filedata
     * @param path  文件路径
     * @param name  文件名称，不带文件后缀
     * @param isReturnPath  是否返回完整地址
     * @return
     */
    public String fileUpload(MultipartFile filedata, String path,
                             String name,boolean isReturnPath) {
        if (filedata == null || filedata.isEmpty()) {
            return "";
        }
        String fileName = filedata.getOriginalFilename();
        name = name + fileName.substring(fileName.lastIndexOf("."));
        File fileDir = new File(path);
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
        FileOutputStream out = null;
        InputStream in = null;
        try {
            out = new FileOutputStream(path + File.separator + name);
            in = filedata.getInputStream();
            byte buffer[] = new byte[1024];
            int len = 0;
            while ((len = in.read(buffer)) > 0) {
                out.write(buffer, 0, len);
            }
            out.flush();
        } catch (Exception e) {
            log.error("", e);
            if(isReturnPath){
                return path + File.separator + name;
            }
            return name;
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (Exception e) {
                    log.error("", e);
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (Exception e) {
                    log.error("", e);
                }
            }
        }
        if(isReturnPath){
            return path + File.separator + name;
        }
        return name;
    }
}